<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.key" placeholder="请输入名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
<!--        <el-button @click="getMessage()">查询</el-button>-->
<!--        <el-button v-if="isAuth('alarmonline:areaalarmonline:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>-->
<!--        <el-button v-if="isAuth('alarmonline:areaalarmonline:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>-->
      </el-form-item>
    </el-form>
    <el-table
      :data="filteredDataList"
      border
      ref="singleTable"
      highlight-current-row
      @current-change="handleCurrentChange"
      :row-class-name="tableRowClassName"
      :header-cell-style="{background:'#17b3a3',color:'#FFFFFF'}"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
<!--      <el-table-column-->
<!--        prop="areaAlarmNo"-->
<!--        header-align="center"-->
<!--        align="center"-->
<!--        label="报警编号">-->
<!--      </el-table-column>-->
      <el-table-column
        prop="areaId"
        header-align="center"
        align="center"
        label="区域编号">
<!--        {{dataList[i].areaId}}-->
      </el-table-column>
      <el-table-column
        prop="areaname"
        header-align="center"
        align="center"
        label="区域名称">
        <!--        {{dataList[i].areaId}}-->
      </el-table-column>
      <el-table-column
        prop="lableId"
        header-align="center"
        align="center"
        label="标签号">
      </el-table-column>
      <el-table-column
        prop="lableEmployid"
        header-align="center"
        align="center"
        label="人员编号">
      </el-table-column>
      <el-table-column
        prop="empname"
        header-align="center"
        align="center"
        label="姓名">
        <!--        {{dataList[i].areaId}}-->
      </el-table-column>
      <el-table-column
        prop="alarmTime"
        header-align="center"
        align="center"
        label="报警时间">
        <template slot-scope="scope">
          {{ scope.row.alarmTime | formatTime }}
        </template>
      </el-table-column>
    </el-table>
 </div>
</template>

<script>
  import AddOrUpdate from './areaalarmonline-add-or-update'
  import $ from 'jquery'

  function isIn (x, xl, xr) {
    if (x >= Math.min(xl, xr) && x <= Math.max(xl, xr)){
      return true;
    } else {
      return false;
    }
  }

  function isInArea (x, y, xl, yl, xr, yr) {
    if (isIn(x, xl, xr)){
      if (isIn(y, yl, yr)){
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  }

  export default {
    data () {
      return {
        dataForm: {
          key: '',
          areaAlarmNo: '',
          areaId: '',
          lableId: '',
          lableEmployid: '',
          alarmTime: '',
          empname: '',
        },
        dataList: [],
        dataPop: [],
        dataList1: [{}],
        dataJson: {
          areaAlarmNo: '',
          areaId: '',
          lableId: '',
          lableEmployid: '',
          alarmTime: ''
        },
        dataListtest: [],
        originalDataList: [],  // 用来存储原始的数据列表
        dataJson1: [],
        alarmNum: 0,
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        path:"ws://10.143.7.73:8089/renren-fast/websocket",
        // path:"ws://10.143.7.73:8089/renren-fast/websocket",
        socket:"",
        displayedNotifications: new Set(), // 存储已显示通知的 Set
        notificationQueue: [], // 通知队列
      }
    },
    components: {
      AddOrUpdate
    },
    computed: {
      filteredDataList() {
        if (this.dataForm.key) {
          return this.dataList.filter(item => item.empname.includes(this.dataForm.key));
        } else {
          return this.dataList;
        }
      }
    },
    mounted () {
      this.testTwo();
      this.init();
    },
    methods: {
      init: function () {
        if(typeof(WebSocket) === "undefined"){
          alert("您的浏览器不支持socket")
        }else{
          // 实例化socket
          this.socket = new WebSocket(this.path)
          // 监听socket连接
          this.socket.onopen = this.open
          // 监听socket错误信息
          this.socket.onerror = this.error
          // 监听socket消息
          this.socket.onmessage = this.getMessage
        }
      },
      open: function () {
        console.log("socket连接成功")
      },
      error: function () {
        console.log("连接错误")
      },
      getMessage: function (event) {
         // console.log(event.data)
        // var alarmArray = [];
        const newAlarm = JSON.parse(event.data);
        this.dataList.push(newAlarm);
        console.log(this.dataList);

        // 检查是否已经显示过相同的通知
        if (!this.displayedNotifications.has(newAlarm.id)) {
          // 添加通知到队列
          this.notificationQueue.push(newAlarm);

          // 将通知标记为已显示
          this.displayedNotifications.add(newAlarm.id);

          // 延迟一段时间后处理通知队列
          if (!this.notificationTimeout) {
            this.processNotificationQueue();
          }
        }
        // 将消息数组转换为JSON字符串，并输出
        // var jsonString = JSON.stringify(alarmArray);
        // this.dataList.push(alarmArray);
        //console.log(this.dataList);
      },

      // 处理通知队列
      processNotificationQueue() {
        if (this.notificationQueue.length > 0) {
          const alarm = this.notificationQueue.shift();
          // 显示通知
          this.showNotification(alarm);

          // 延迟一段时间后继续处理队列中的通知
          this.notificationTimeout = setTimeout(() => {
            this.notificationTimeout = null;
            this.processNotificationQueue();
          }, 500); // 调整延迟时间以控制通知显示速度
        }
      },
      // 显示通知
      showNotification(alarm) {
        //弹窗
        const h = this.$createElement;
        this.$notify({
          dangerouslyUseHTMLString: true,
          duration: 3000,
          title: '警告',
          message: h('el-table', {props:{data:
              this.dataList,border:true,height:"250",size:"mini"}, style:{with:'100%'}}, [
            h('el-table-column', {props:{prop: "areaname",label:"报警区域"}},{}),
            h('el-table-column', {props:{prop: "empname",label:"姓名"}},{}),
            h('el-table-column', {props:{ prop: "alarmTime", label: "时间" },
              scopedSlots: {
                default: (scope) => {
                  // 使用过滤器格式化时间
                  return this.$options.filters.formatTime(scope.row.alarmTime);
                }
              }
            },{}),
          ]),
          type: 'warning'
        });
      },
      send: function () {
        this.socket.send(params)
      },
      close: function () {
        console.log("socket已经关闭")
      },
      //  奇偶行背景色不同
      setCurrent(row) {
        this.$refs.singleTable.setCurrentRow(row);
      },
      handleCurrentChange(val) {
        this.currentRow = val;
      },
      tableRowClassName({row, rowIndex}) {
        if ((rowIndex + 1) % 2 === 0) {
          return 'success-row';
        }
        return '';
      },

      //测试新方法
      async testTwo(){
        // 清空数据表
        await this.$http({
          url: this.$http.adornUrl(`/alarmonline/areaalarmonline/remove`),
          method: 'post',
          async:false
        });
       // let that = this;
        try {
          const data = await this.$http({
            url: this.$http.adornUrl('/area/area/list'),
            method: 'get',
            params: this.$http.adornParams({
              'page': this.pageIndex,
              'limit': this.pageSize,
              'key': this.dataForm.key
            })
          });
          const data1 = await this.$http({url: this.$http.adornUrl('/labonin/lableonlineinfo/iswork'), type:'GET', async:true});

          //数据格式：[{"uuid":"b9809a0e2dc44a509cc657b4e1a337cc","cardId":131249,"personName":"零件托盘11","posX":1229.117081,"posY":88.575989,"posTime":1694510800318,"isWork":0},{"uuid":"604f9c6baf4047b8ac876b6e64bac39c","cardId":131384,"personName":"BC0148X05","posX":1108.932858,"posY":151.872953,"posTime":1694515624665,"isWork":1},{"uuid":"de03e927fdc34489861dccb976f350a4","cardId":131960,"personName":"BC0097X05","posX":1075.67461,"posY":138.266143,"posTime":1694515627878,"isWork":1},{"uuid":"3bdb92e63a3f4d21bd32df478dc06014","cardId":132097,"personName":"吕志全","posX":1116.8938,"posY":191.845468,"posTime":1694515623043,"isWork":1},{"uuid":"3d87ae429ee148d1a167a0aae67dc212","cardId":132111,"personName":"BC0092D15","posX":1144.660762,"posY":206.727489,"posTime":1694515621822,"isWork":1},{"uuid":"b2a17c0a6a9247eb9714bca5a9b59fd1","cardId":132513,"personName":"货架17","posX":1115.0,"posY":155.0,"posTime":1694506406981,"isWork":0},{"uuid":"8b1b406b48c64f459c3613c640e2009a","cardId":133479,"personName":"BC0096D15","posX":1157.497213,"posY":123.553513,"posTime":1694515630370,"isWork":1}]
          // 在这里处理数据
          // ...
          var json = data.data.page.list;
          //data.data：{"msg":"success","code":0,"page":{"totalCount":2,"pageSize":10,"totalPage":1,"currPage":1,"list":[{"areaNo":10001,"areaId":"10001","areaName":"project1-1","areaPosX1":0.0,"areaPosY1":104.0,"areaPosX2":1350.0,"areaPosY2":230.0},{"areaNo":10002,"areaId":"10002","areaName":"project1-2","areaPosX1":450.0,"areaPosY1":300.0,"areaPosX2":1000.0,"areaPosY2":400.0}]}}
          // console.log(json)
          // 取报警区域的坐标
          // console.log(json[0].areaPosX1)
          // console.log(json[0].areaPosY1)
          // console.log(json[0].areaPosX2)
          // console.log(json[0].areaPosY2)
          // var json1 = data1.data.page.list;
          var json1 = data1.data;
          // console.log(json1)
          // labelonline的坐标
          // console.log(json1[0].labelPosX)
          // console.log(json1[0].labelPosY)
          // console.log(json1[1].labelPosX)
          // console.log(json1[1].labelPosY)
          for (var i = 0; i < json1.length; i++) {
            for (var j = 0; j < json.length; j++) {
              // console.log(json1[i].posX, json1[i].posY, json[j].areaPosX1, json[j].areaPosY1, json[j].areaPosX2, json[j].areaPosY2)
              // if (isInArea(json1[i].labelPosX, json1[i].labelPosY, json[j].areaPosX1, json[j].areaPosY1, json[j].areaPosX2, json[j].areaPosY2)){
              if (isInArea(json1[i].posX, json1[i].posY, json[j].areaPosX1, json[j].areaPosY1, json[j].areaPosX2, json[j].areaPosY2)){
                // console.log(json1[i].posX, json1[i].posY, json[j].areaPosX1, json[j].areaPosY1, json[j].areaPosX2, json[j].areaPosY2)
                // console.log('坐标点[' + json1[i].posX + ', ' + json1[i].posY + ']在报警区域' + json[j].areaId + '内！');
                // console.log('坐标点[' + json1[i].posX + ', ' + json1[i].posY + ']在区域' + json[j].areaId + '内！');

                this.$http({
                  url: this.$http.adornUrl(`/alarmonline/areaalarmonline/add`),
                  method: 'post',
                  async: false,
                  data: this.$http.adornData({
                    'areaAlarmNo': Date.now(),
                    'areaId': data.data.page.list[j].areaId,
                    'areaname': data.data.page.list[j].areaName,
                    'lableId':  data1.data[i].cardId,
                    'lableEmployid': data1.data[i].cardId,
                    'empname': data1.data[i].personName,
                    'alarmTime': data1.data[i].posTime
                  })
                })
              }
            }
          }

        } catch (error) {
          console.error("An error occurred:", error);
        }
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/alarmonline/areaalarmonline/selectByEmpName'),
          method: 'get',
          async: false,
          params: this.$http.adornParams({
            'empName': this.dataForm.key
          })
        }).then(({data}) => {
          //如果data不为[]，则将data赋值给dataList，否则调用getMessage()方法
          if (data != null) {
            this.dataList = data
          } else {
            // this.getMessage()
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.areaalarmNo
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/alarmonline/areaalarmonline/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      }
    }
    // beforeDestroy () {
    //   clearInterval(this.timer);
    //   this.timer = null;
    // }
  }
</script>
<style lang="scss">
.tr-color-0 {
  background: #f0f0f0;
}
.tr-color-1 {
  background: #fff;
}
.el-table .success-row {
  background: #DFEAF5;
}
</style>
